package jwt

import (
	"github.com/dgrijalva/jwt-go"
	"time"
)

type Claims struct {
	Uid       uint   `json:"uid"`
	Name      string `json:"name"`
	Role      string `json:"role"`
	ExpiresAt int64  `json:"exp"`
}

func (c Claims) Valid() error {
	return nil
}

func CreateToken(secretKey string, uid uint, name, role string, exp int) (string, error) {
	claims := Claims{
		Uid:       uid,
		Name:      name,
		Role:      role,
		ExpiresAt: time.Now().Add(time.Minute * time.Duration(exp)).Unix(),
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenStr, err := token.SignedString([]byte(secretKey))
	if err != nil {
		return "", err
	}
	return tokenStr, nil
}

func ParseToken(tokenStr string, secretKey string) (jwt.MapClaims, error) {

	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})
	if err != nil {
		return nil, err
	}

	mapClaims := token.Claims.(jwt.MapClaims)
	return mapClaims, nil
}
